import { useState, createContext } from 'react';

import Form from './Form';
import List from './List';

//创建并导出孙组件需要的上下文对象
export const ListContext = createContext({});

function TodoList() {
  const [addCount, setAddCount] = useState(0);
  const [removeCount, setRemoveCount] = useState(0);
  const [todoList, setTodoList] = useState([]);

  const onAddTodo = (todo) => {
    setTodoList((todoList) => [...todoList, todo]);
    setAddCount(addCount + 1);
  };

  const onToggleTodo = (id) => {
    setTodoList((todoList) => {
      return todoList.map((item) => {
        item.id === id && (item.completed = !item.completed);
        return item;
      });
    });
  };

  const onRemoveTodo = (id) => {
    setTodoList((todoList) => todoList.filter((item) => item.id !== id));
    setRemoveCount(removeCount + 1);
  };

  return (
    <div className="todo">
      <Form addTodo={onAddTodo} />
      {/* 在单支组件树情况下可以使用Provider将父组件的方法传递到孙组件中 */}
      <ListContext.Provider
        value={{ toggleTodo: onToggleTodo, removeTodo: onRemoveTodo }}
      >
        <List
          addCount={addCount}
          removeCount={removeCount}
          todoList={todoList}
        />
      </ListContext.Provider>
    </div>
  );
}

export default TodoList;
